<template>
  <div class="home">
    <div class="get-code">
      <input type="text" v-model="phone" placeholder="请输入手机号后四位查询" />
      <div class="get-btn" @click="getRedeCode"><img src="../assets/get.png" /></div>
    </div>
    <div class="show-msg">
      <div class="msg" :class="tipsType" v-if="showMsg">
        {{ message }}
      </div>
    </div>
    <div class="code-wrap" v-show="codeList.length > 0">
      <div class="code-item" v-for="(item, index) in codeList" :key="index">
        <div class="code-item-info">
          <div class="gift-info">礼品类型：<span>{{ typeFormat(item.phone_type) }}</span></div>
          <div class="copy-btn" @click="copyCode(item.get_code)">复制兑换码</div>
        </div>
        <div class="gift-info">用户手机：<span>{{ item.phone
            }}</span></div>
        <div class="gift-info">兑换编码：<span class="code-style">{{ item.get_code
            }}</span></div>
        <div class="gift-info">领取日期：<span>{{ dayjs(item.usedAt).format('YYYY-MM-DD HH:mm:ss')
            }}</span></div>
      </div>
    </div>
    <div class="get-step" @click="ruleVisible = true"><img src="../assets/step.png" /></div>
    <div class="dialog" v-if="ruleVisible">
      <div class="back-btn" @click="ruleVisible = false">返回页面</div>
      <div class="content"><img src="../assets/rule.jpg" /></div>
    </div>
  </div>
</template>

<script setup name="HomeView">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
import useClipboard from 'vue-clipboard3'

const phone = ref('')
const message = ref('')
const ruleVisible = ref(false)
const showMsg = ref(false)
const tipsType = ref('error')
const codeList = ref([])
const { toClipboard } = useClipboard()
const copyCode = async (text) => {
  try {
    await toClipboard(text)
    showTips('复制成功！', 'success')
  } catch (e) {
    console.error('复制失败:', e)
  }
};

// 获取微信配置
const getWechatConfig = async () => {
  const url = window.location.href.split('#')[0]
  const { status, data } = await axios.get('/wechat/getShareConfig', {
    params: {
      url,
    },
  })
  if (status === 200 && data) {
    const { appId, timestamp, nonceStr, signature } = data.data

    // 初始化微信 JS-SDK
    // eslint-disable-next-line no-undef
    wx.config({
      debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来，若要查看传入的参数，可以在 pc 端打开，参数信息会通过 log 打出，仅在 pc 端时才会打印。
      appId, // 必填，公众号的唯一标识
      timestamp, // 必填，生成签名的时间戳
      nonceStr, // 必填，生成签名的随机串
      signature, // 必填，签名
      jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'previewImage'], // 必填，需要使用的 JS 接口列表
    })
    // eslint-disable-next-line no-undef
    wx.ready(() => {
      const shareData = {
        title: '兑换礼来啦', // 分享标题
        desc: '快来领取兑换码', // 分享描述
        link: url, // 分享链接
        imgUrl: 'https://kuyuncloud.com/get-redemption/share.png', // 分享图标URL
        success: () => {
          // console.log('分享成功')
        },
      }
      // eslint-disable-next-line no-undef
      wx.updateAppMessageShareData(shareData) // 分享给朋友
      // eslint-disable-next-line no-undef
      wx.updateTimelineShareData(shareData) // 分享到朋友圈
    })
  }
}

const showTips = (msg, type) => {
  message.value = msg
  tipsType.value = type
  showMsg.value = true
  setTimeout(() => {
    showMsg.value = false
    message.value = ''
  }, 2500)
}

const getRedeCode = async () => {
  codeList.value = []
  if (!phone.value) {
    showTips('手机号码不能为空！', 'error')
    return
  }
  if (phone.value.length > 4) {
    showTips('请输入手机号码后四位！', 'error')
    return
  }
  const { status, data } = await axios.get('/redemption/findCodeByPhone', {
    params: {
      phone: phone.value,
    },
  })
  if (status === 200 && data) {
    if (data.data.length > 0) {
      codeList.value = data.data
    } else {
      showTips('未找到该手机号的礼品信息！', 'error')
    }
  }
}

const typeFormat = (type) => {
  let value = ''
  if (type === 1) {
    value = '开卡礼'
  } else if (type == 2) {
    value = '达标礼'
  }
  return value
}

const isWeChatEnvironment = () => {
  const userAgent = navigator.userAgent.toLowerCase()
  return userAgent.indexOf('micromessenger') !== -1
}

onMounted(() => {
  if (isWeChatEnvironment()) {
    getWechatConfig()
  }
})
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100vh;
  background: url(../assets/bg.png) no-repeat center top;
  background-size: 100% auto;

  .get-code {
    width: 80%;
    display: flex;
    margin: 0 auto;
    padding-top: 20vh;
    padding-bottom: 30px;

    input {
      flex: 1;
      height: 64px;
      line-height: 64px;
      margin-right: 15px;
      border-radius: 10px;
      text-indent: 15px;
      outline: none;
      border: none;
      font-size: 26px;
      color: #10325c;
    }

    input:-webkit-input-placeholder {
      color: #10325c;
    }

    .get-btn {
      width: 30%;
    }
  }

  .show-msg {
    width: 80%;
    height: 70px;
    margin: 0 auto;

    .msg {
      padding: 4px 15px;
      font-size: 26px;
      border-radius: 8px;
      color: #fff;
      text-align: center;

      &.success {
        background-color: #07c160;
      }

      &.error {
        background-color: #ff0000;
      }
    }
  }

  .code-wrap {
    width: 80%;
    // height: 32vh;
    margin: 0 auto;
    border-radius: 10px;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 15px;
    box-sizing: border-box;

    .code-item {
      padding: 10px;
      background: linear-gradient(to bottom, #fcedc8, #fadb8e);
      border-radius: 8px;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .gift-info {
        font-size: 14px;
        color: #3e3e3e;

        span {
          color: #3e3e3e;
          font-size: 16px;
        }

        span.code-style {
          background-color: #eee;
          color: #10325c;
          font-weight: 600;
          border-radius: 6px;
          padding: 2px 6px;
        }
      }

      .code-item-info {
        display: flex;
        justify-content: space-between;

        .copy-btn {
          padding: 0 4px;
          border: 1px solid #10325c;
          color: #10325c;
          border-radius: 4px;
          font-size: 16px;
          text-align: center;
        }
      }

    }

    .code-tips {
      padding-top: 20px;
      color: #10325c;
    }
  }

  .get-step {
    width: 75%;
    padding-top: 100px;
    margin: 0 auto;
  }

  .dialog {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    background: rgba(0, 0, 0, 0.5);

    .content {
      width: 100%;
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
    }

    .back-btn {
      width: 150px;
      height: 56px;
      line-height: 56px;
      font-size: 28px;
      color: #10325c;
      background-color: #fff;
      border-radius: 8px 0 0 8px;
      text-align: center;
      position: fixed;
      top: 5%;
      right: 0;
      cursor: pointer;
      z-index: 120;
    }
  }

}
</style>
